<template>
  <div>
    <Header
      :isGoBack="false"
      :class="isHeaderFixed ? 'fixed-header-shadow' : 'fixed-header'"
    >
      <template v-slot:left>
        <div>
          {{ checkedBookData.edition_name }}- {{ checkedBookData.grade_name }}>
          {{ $store.getters.categoryList[category].title }}(普通模式)
        </div>
      </template>
      <template v-slot:right>
        <div class="test-btn">
          <span>计时：{{ testTime | filterTime }}</span>
          <span class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="submitPaper"
              >交卷</el-button
            >
          </span>
          <span class="btn-bg ml20">
            <el-button
              class="button button-border-second"
              @click="goStudyCenter"
            >
              返回学习中心
            </el-button>
          </span>
        </div>
      </template>
    </Header>
    <div class="w1200 general-test-box">
      <div id="printTest" ref="printTest" class="general-test">
        <div
          class="question-type-container"
          v-for="(quetionType, index) in questionList"
          :key="quetionType.question_type"
        >
          <div class="type-title">
            <span>{{ index + 1 }}.</span>
            {{ typeObj[quetionType.question_type] }}
            <span>
              <span
                class="reminder-text"
                v-if="
                  quetionType.question_type == 1 ||
                    quetionType.question_type == 2 ||
                    quetionType.question_type == 3
                "
              >
                (Tab跳转下一题,四个选项快捷键1/2/3/4)
              </span>
              <span class="reminder-text" v-else>(Tab跳转下一题)</span>
            </span>
          </div>
          <ul class="question-list">
            <li
              class="question"
              :class="
                question.allIndex == nowIndex
                  ? 'question-ing '
                  : question.studentAnswer
                  ? 'checked-question'
                  : ''
              "
              v-for="(question, index2) in quetionType.question_info_list"
              :key="question.word_id + '' + question.question_type"
              @click="changeAnswer(question.allIndex)"
            >
              <TestQuestion
                :ref="'question' + question.allIndex"
                :index="index2 + 1"
                :question="question"
                @changeAnswer="changeAnswer"
                @changeStudentAnswer="changeStudentAnswer"
              ></TestQuestion>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import TestQuestion from "../components/TestQuestion";
import { getPaperData, startPaperTest, checkPaperData } from "@/api/index";
import EventBus from "@/assets/js/eventBus";
export default {
  data() {
    return {
      paperData: {},
      questionList: [],
      typeObj: {
        0: "记忆",
        1: "英译汉",
        2: "汉译英",
        3: "听力理解",
        4: "听写",
        5: "默写",
      },
      nowIndex: 0,
      allNum: 0,
      testTime: 0,
      timer: null,
      checkedBookData: null,
      unitId: null,
      category: null,
      source: null,
      testLoading: false,
      isHeaderFixed: false,
      submitReminder: true,
      isOpenMessageBox: false,
    };
  },
  computed: {
    questionType() {
      let nowType = "";
      let nextType = "";
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (question.allIndex == this.nowIndex) {
            nowType = question.question_type;
          }
          if (question.allIndex == this.nowIndex + 1) {
            nextType = question.question_type;
          }
        });
      });
      return {
        nowType,
        nextType,
      };
    },
  },
  components: {
    Header,
    TestQuestion,
  },
  methods: {
    printTest() {
      // PrintJS({
      //   printable: "printTest",
      //   type: "html",
      //   documentTitle: "测验",
      //   // scanStyles: false,
      //   // 继承原来的所有样式
      //   // targetStyles: ["*"],
      //   // css: "/assets/css/print.css",
      // });
      this.$print(this.$refs.printTest);
      // window.print();
    },
    goStudyCenter() {
      this.$confirm(`试卷还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          if (this.$route.query.backName) {
            this.$router.push({
              name: "naturalSpell",
            });
            return;
          }
          this.$router.push({
            name: "studyCenter",
          });
        })
        .catch(() => {
          return false;
        });
    },
    getTestPaper() {
      let data = {
        category: this.category,
        book_id: this.checkedBookData.book_id,
        unit_id_list: this.unitId, //2229 2230
        mode: 0,
        source: this.source,
      };
      if (this.category == 24) {
        data.question_type_list = this.$route.query.questionType
          ? String(this.$route.query.questionType)
              .split(",")
              .map(Number)
          : [1, 2, 3, 4, 5];
      }
      EventBus.$emit("openLoading", {});
      getPaperData(data)
        .then((res) => {
          EventBus.$emit("closeLoading");
          if (res.code == 200) {
            startPaperTest({
              english_test_id: res.data.english_test_id,
            }).then((res1) => {
              if (res1.code == 200) {
                this.testTime = 0;
                this.timerFun();
              }
            });

            this.paperData = res.data;
            this.questionList = res.data.question_info_type_list;
            let allIndex = -1;
            this.questionList.forEach((questionType) => {
              questionType.question_info_list.forEach((question) => {
                question.studentAnswer = "";
                allIndex++;
                question.allIndex = allIndex;
                question.phonetic =
                  this.$store.getters.isBritish == 1
                    ? question.phonetic_british
                    : question.phonetic_american; //音标
                question.audioURL =
                  this.$store.getters.isBritish == 1
                    ? question.en_url
                    : question.us_url; //音频
              });
            });
            this.allNum = allIndex;
            this.$nextTick(() => {
              if (
                this.$refs[`question${this.nowIndex}`] &&
                this.$refs[`question${this.nowIndex}`][0]
              ) {
                this.$refs[`question${this.nowIndex}`][0].inputFocus();
              }
              if (this.questionType.nowType == 3) {
                if (
                  this.$refs[`question${this.nowIndex}`] &&
                  this.$refs[`question${this.nowIndex}`][0]
                ) {
                  this.$refs[`question${this.nowIndex}`][0].playAudio();
                }
              }
            });
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading");
        });
    },
    changeAnswer(allIndex) {
      if (this.nowIndex !== allIndex) {
        this.nowIndex = allIndex;
      }
    },
    timerFun() {
      this.timer = setInterval(() => {
        this.testTime++;
        if (
          this.testTime > this.paperData.test_time - 10 &&
          // this.testTime <= 10 &&
          this.submitReminder &&
          !this.isOpenMessageBox
        ) {
          this.isOpenMessageBox = true;
          this.submitReminder = false;
          this.$confirm(`考试即将超时,即将自动交卷`, "提示", {
            confirmButtonText: "立即交卷",
            cancelButtonText: "取消",
            closeOnHashChange: true,
            beforeClose: (action, instance, done) => {
              this.isOpenMessageBox = false;
              done();
            },
          })
            .then(() => {
              this.postPaper();
              clearInterval(this.timer);
            })
            .catch(() => {});
        } else if (this.testTime >= this.paperData.test_time - 3) {
          this.$msgbox.close();
          clearInterval(this.timer);
          this.postPaper();
        }
      }, 1000);
    },
    submitPaper() {
      let number = 0;
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (!question.studentAnswer) {
            number++;
          }
        });
      });
      if (!this.isOpenMessageBox) {
        this.isOpenMessageBox = true;
        this.$confirm(
          `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            beforeClose: (action, instance, done) => {
              this.isOpenMessageBox = false;
              done();
            },
          }
        )
          .then(() => {
            this.postPaper();
          })
          .catch(() => {
            return false;
          });
      }
    },
    postPaper() {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (
            question.question_type == 1 ||
            question.question_type == 2 ||
            question.question_type == 3
          ) {
            let answer = question.answer_list.filter((answer) => {
              return (
                question.studentAnswer ==
                (answer.word_id || answer.word_name || answer.paraphrase)
              );
            });
            question.student_answer_list = answer;
          } else if (
            question.question_type == 4 ||
            question.question_type == 5
          ) {
            question.student_answer_list = question.studentAnswer
              ? [{ word_name: question.studentAnswer.trim() }]
              : [];
          }
        });
      });
      // let useTime = this.paperData.test_time - this.testTime;
      let useTime = this.testTime;
      let data = {
        english_test_id: this.paperData.english_test_id,
        book_id: this.checkedBookData.book_id,
        source: this.source,
        use_time: useTime,
        unit_id_list: this.unitId,
        student_question_info_list: this.questionList,
      };
      EventBus.$emit("openLoading", {});
      checkPaperData(data)
        .then((res) => {
          EventBus.$emit("closeLoading");
          if (res.code == 200 && res.data && res.data.question_info_type_list) {
            this.testLoading = true;
            res.data.test_time = this.paperData.test_time;
            res.data.useTime = useTime;
            localStorage.setItem("paperRes", JSON.stringify(res));
            clearInterval(this.timer);
            this.$router.push({
              name: "testReport",
              query: this.$route.query,
            });
          } else if (res.data.is_finish) {
            this.$alert("考试已结束");
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading");
        });
    },
    changeStudentAnswer(studentAnswer, allIndex) {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (question.allIndex == allIndex) {
            question.studentAnswer = studentAnswer;
            return;
          }
        });
      });
    },
    watchKeyDown(e) {
      if (this.isOpenMessageBox) {
        return;
      }
      if (e.keyCode == 17) {
        if (
          this.$refs[`question${this.nowIndex}`] &&
          this.$refs[`question${this.nowIndex}`][0]
        ) {
          this.$refs[`question${this.nowIndex}`][0].playAudio();
        }
      }
      if (e.keyCode == 9) {
        if (
          this.questionType.nextType == 1 ||
          this.questionType.nextType == 2 ||
          this.questionType.nextType == 3 ||
          this.questionType.nextType == ""
        ) {
          this.stopEvent(e);
          if (
            this.questionType.nowType == 4 ||
            this.questionType.nowType == 5
          ) {
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].inputBlur();
            }
          }
          if (this.nowIndex + 1 > this.allNum) {
            this.nowIndex = 0;
          } else {
            this.nowIndex++;
          }
          if (this.questionType.nowType == 3) {
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].playAudio();
            }
          }
          this.qScrollToView();
        }

        if (
          this.$refs[`question${this.nowIndex}`] &&
          this.$refs[`question${this.nowIndex}`][0]
        ) {
          this.$refs[`question${this.nowIndex}`][0].inputFocus();
        }
      }
      if (
        this.questionType.nowType == 1 ||
        this.questionType.nowType == 2 ||
        this.questionType.nowType == 3
      ) {
        this.stopEvent(e);
        if (e.keyCode == 49 || e.keyCode == 97) {
          this.checkAnswer(1);
        }
        if (e.keyCode == 50 || e.keyCode == 98) {
          this.checkAnswer(2);
        }
        if (e.keyCode == 51 || e.keyCode == 99) {
          this.checkAnswer(3);
        }
        if (e.keyCode == 52 || e.keyCode == 100) {
          this.checkAnswer(4);
        }
      }

      //97-100
    },
    //阻止默认事件
    stopEvent(e) {
      if (e && e.preventDefault) {
        e.preventDefault();
      } else {
        window.event.returnValue = false;
      }
    },
    //滚动到到当前
    qScrollToView() {
      if (
        this.$refs[`question${this.nowIndex}`] &&
        this.$refs[`question${this.nowIndex}`][0]
      ) {
        console.log(
          this.$refs[`question${this.nowIndex}`][0].$el.scrollIntoView
        );
        this.$refs[`question${this.nowIndex}`][0].$el.scrollIntoView(false);
      }
    },
    // 1/2/3/4选择选项
    checkAnswer(num) {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (
            question.allIndex == this.nowIndex &&
            question.answer_list &&
            question.answer_list[num - 1]
          ) {
            let answer = question.answer_list[num - 1];
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].studentAnswer =
                answer.word_id || answer.word_name || answer.paraphrase;
              this.$refs[`question${this.nowIndex}`][0].changeStudentAnswer();
            }
          }
        });
      });
    },
    scrollBehavior() {
      let dom = document.getElementById("app");
      const top = dom.pageYOffset || dom.scrollTop || dom.scrollTop;
      if (top > 0) {
        this.isHeaderFixed = true;
      } else {
        this.isHeaderFixed = false;
      }
    },
  },
  filters: {
    filterTime(val) {
      let hours = parseInt(val / 3600);
      if (hours < 10) {
        hours = "0" + hours;
      }
      let minutes = parseInt((val % 3600) / 60);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      let seconds = parseInt(val % 60);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return hours + ":" + minutes + ":" + seconds;
    },
  },
  mounted() {
    window.addEventListener("keydown", this.watchKeyDown);
    document
      .getElementById("app")
      .addEventListener("scroll", this.scrollBehavior);
  },
  beforeDestroy() {
    window.removeEventListener("keydown", this.watchKeyDown);
    document
      .getElementById("app")
      .removeEventListener("scroll", this.scrollBehavior);
    clearInterval(this.timer);
    if (this.isOpenMessageBox) {
      this.$msgbox.close();
    }
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.category = Number(this.$route.query.category);
    this.source = this.$store.getters.categoryList.filter((item) => {
      return item.category == this.category;
    })[0].source;
    this.unitId = this.$route.query.unitId
      ? String(this.$route.query.unitId)
          .split(",")
          .map(Number)
      : null;
    this.getTestPaper();
  },
  watch: {
    // nowIndex: {
    //   handler() {
    //     if (this.questionType.nowType == 3) {
    //       if (
    //         this.$refs[`question${this.nowIndex}`] &&
    //         this.$refs[`question${this.nowIndex}`][0]
    //       ) {
    //         this.$refs[`question${this.nowIndex}`][0].playAudio();
    //       }
    //     }
    //   },
    //   // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
    //   immediate: true,
    // },
  },
};
</script>
